package top.asteam.cloud.config;

import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import top.asteam.entity.CommonResult;

import java.nio.charset.StandardCharsets;

/**
 * @Author Rock Wang
 * @Time 2021/5/13
 */
@Component
public class MyLogGateWayFilter implements GlobalFilter, Ordered {

    private  final Logger logger = LoggerFactory.getLogger(MyLogGateWayFilter.class);
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uname = exchange.getRequest().getQueryParams().getFirst("uname");
        if (StringUtils.isEmpty(uname)){
            logger.error("错误，uname为空!!!");
            ServerHttpResponse response = exchange.getResponse();
            // 控制响应头的方式拒绝请求
            //response.setStatusCode(HttpStatus.NOT_ACCEPTABLE);
            //return response.setComplete();

            // status200,配置自定义响应
            CommonResult data = CommonResult.serverError("uname传一下呗!");
            DataBuffer buffer = exchange.getResponse().bufferFactory()
                    .wrap(JSONObject.toJSONString(data).getBytes(StandardCharsets.UTF_8));
            return response.writeWith(Mono.just(buffer));
        }

        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
